layui.config({base: top.basePath+'/static/common/layui/js/'})
    .define(['form','newLayer','newAjax','newDate','tableKit'], function(exports) {
    "use strict";

    var $=layui.jquery;

    /**
     * @constructor newTable 构造函数
     */
    var NewForm = function() {
    	this.target=layui.form;
        this.layer=layui.newLayer
        this.config={
            openLayerVar:'newTable' // 打开的layer中数据结构的layui 变量
        }
    };

    /**
     * @description 数据填充
     * @param {Object} dbData
     */
    NewForm.prototype.val = function(dbData) {
        var that=this;
        var data=JSON.parse(dbData);
        that.target.val('dataForm',data);//lay-filter="dataForm"

        // 必填高亮提醒
        var $form = $('form');
        $form.find('[lay-verify^="required"]').each(function (i) {
            $(this).parent().parent().find('label').prepend('<font color="red">* </font>')
        });

        //添加按钮
        var buttonDiv = $form.children().last().children().last();
        buttonDiv.css('float','right').css('margin-right','300px')
            .append('<button type="button" id="close" class="layui-btn layui-btn-normal">关闭</button>');

        buttonDiv.on('click','#close',function () {
            closeCurrentLayer();
        })

        buttonDiv.children().eq(1).removeClass('layui-btn-primary').addClass('layui-btn-danger')

        return that;
    };
    /**
     * @description 绑定事件
     * @param {Object} dbData
     */
    NewForm.prototype.onForm = function(reg, f) {
        var that=this;
        that.target.on(reg,function (data) {
            f(data);
        });
        return that;
    };

    NewForm.prototype.buildChildAddress=function(where, code) {
        var that=this;
        $.post(top.basePath+"plat/area/findAreaByParentCode.html", {'code':code},function (result) {
            if(result && result.length>0){
                var options = '<option value="">请选择</option>';
                for(var i in result){
                    options += '<option value="'+result[i].areaCode+'">'+result[i].name+'</option>'
                }
                $('select[name="'+where+'"]').html(options);
                that.target.render('select');
            }
        });
        return that;
    }

    /**
     * @description 重新渲染 select标签
     * @param {Object} dbData
     */
    NewForm.prototype.renderSelect = function(dbData) {
        var that=this;
        var data=JSON.parse(dbData);
        if(data.id){
            $("select").each(function () {
                var select=$(this);
                select.val(data[select.prop("name")]);
            })
            that.target.render('select');
        }
        return that;
    };

    /**
     *  渲染 时间 选择 input
     * @param inputEle
     * @returns {NewForm}
     */
    NewForm.prototype.renderDateInput = function(inputEle) {
        var that=this;
        $(inputEle).on('click',function () {
            var input=$(this);
            layui.newDate.render({
                elem: inputEle
                ,isInitValue: input.val()
            });
        })
        return that;
    };
    /**
     * 渲染 需要选择code name 回填的input
     * @param inputEle
     * @returns {NewForm}
     */
    NewForm.prototype.renderChooseInput = function(inputEle, title, url,vmVar) {
        var that=this;

        $(inputEle).on('click',function () {
            var input=$(this);
            that.openChooseLayerSelectRows(title,url,true,function (row) {
                input.prev().val(row.code);
                input.val(row.name);
                if(vmVar){
                    vmVar[input.prop('name')]=row.name;
                    vmVar[input.prop('name').replace('Name','Code')]=row.code;
                }
            })
        });
        return that;
    };

    NewForm.prototype.renderChooseInputWithId = function(inputEle, title, url, dataTable) {
        var that=this;

        $(inputEle).on('click',function () {
            var input=$(this);
            layui.newLayer.open({
                title: title,
                content: url,
                btn:['确定'],
                yes:function (index,openLayer) {
                    debugger
                    var rows= openLayer.find("iframe")[0].contentWindow.layui['table'].checkStatus(dataTable||'dataTable').data;
                    if(!rows && rows.length!=1)return;
                    input.prev().val(rows[0].id);
                    input.val(rows[0].name);
                    layui.layer.close(index);
                }
            });
        });
        return that;
    };



    /**
     * @description 提交表单
     * @param {Object} dbData
     */
    NewForm.prototype.onSubmit = function(url, success, fail) {
        var that=this;
        //监听提交
        that.target.on('submit(dataForm)', function(data){
            layui.newAjax.post(url,data.field,
                function (result) {
                    var useLayer = parent.layer || layui.layer;
                    var table=parent.layui.newTable||parent.layui.newTreeTable;
                    table.refreshTable();
                    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                    parent.layer.close(index);

                    if(success){
                        success(result);
                    }
                    useLayer.msg(data.field.id ? "更新成功！" : "新增成功！");

                },function (message) {
                    if(fail){
                        fail();
                    }
                    var useLayer = parent.layer || layui.layer;
                    useLayer.alert(message);
                })

            return false;
        });
    };

    /**
     * 开启新的图层，选择新图层中的行数据后，点确定按钮调用回调方法，回调方法参数为选中的行数据
     *  needSingle=false  方法参数为选中的行数据数组
     *  needSingle=true  方法参数为选中的单行数据
     * @param title 图层名称
     * @param url 图层内容
     * @param needSingle 是否只能单选
     *
     * @param callBack 回调方法
     */
    NewForm.prototype.openChooseLayerSelectRows=function (title,url,needSingle,callBack) {
        var that=this;
        that.layer.open({
            title: title,
            content: url,
            btn:['确定'],offset: '20px',
            yes:function (index,openLayer) {
                var rows=openLayer.find("iframe")[0].contentWindow.layui[that.config.openLayerVar].getSelectedRows(needSingle);
                if(!rows)return;
                callBack(rows);
                that.layer.close(index);
            }
        });

        return that;
    }

    /**
     * 开启新的图层，选择新图层中的行数据后，点确定按钮调用回调方法，回调方法参数为选中行的id数组
     * @param title 图层名称
     * @param url 图层内容
     * @param callBack 回调方法
     */
    NewForm.prototype.openChooseLayerSelectIds=function (title,url,callBack) {
        var that=this;
        that.layer.open({
            title: title,
            content: url,offset: '20px',
            btn:['确定'],
            yes:function (index,openLayer) {
                var ids=openLayer.find("iframe")[0].contentWindow.layui[that.config.openLayerVar].getSelectedRowIds();
                if(!ids)return;
                callBack(index,openLayer,ids);
            }
        });

        return that;
    }

    var newForm=new NewForm();

    exports('newForm', newForm);
});